
package com.itheima.task;


import com.itheima.common.utils.AliOssUtil;

import com.itheima.controllerweb.SetmealController;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.impl.SetmealServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;





import com.itheima.common.utils.AliOssUtil;
import com.itheima.controllerweb.SetmealController;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.impl.SetmealServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Set;
/**
 * 定时清理垃圾图片
 */



@Configuration
@EnableScheduling
@Slf4j
public class CleanImgTask {

/*private final AliOssUtil aliOssUtil;
    private final RedisTemplate<String, String> redisTemplate;
    private final SetmealMapper setmealMapper;

    @Autowired
    public CleanImgTask(AliOssUtil aliOssUtil, RedisTemplate<Object, Object> redisTemplate, RedisTemplate<String, String> redisTemplate1, SetmealMapper setmealMapper) {
        this.aliOssUtil = aliOssUtil;
        this.redisTemplate = redisTemplate1;
        this.setmealMapper = setmealMapper;
    }*/

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private SetmealMapper setmealMapper;


    @Scheduled(cron = "0 0 1 * * ?")    //每天晚上1点执行
//    @Scheduled(cron = "0 0/1 * * * ?")   //测试,每分钟执行
    public void cleanSetmealImg() {
        log.info("执行 清理垃圾图片 任务");
        //求差集
        Set<String> trash = redisTemplate.opsForSet().difference(SetmealController.ALL_IMG_KEY, SetmealServiceImpl.USED_IMG_KEY);
        if (trash != null && !trash.isEmpty()) {

            log.info("清理了 {} 张图片",trash.size());
            for (String fileName : trash) {
                //删除差集的图片
                aliOssUtil.delete(fileName);
                redisTemplate.opsForSet().remove(SetmealController.ALL_IMG_KEY,fileName);
            }

        }else{
            log.info("没有发现垃圾图片");
        }
    }
}


